from rest_framework.views import APIView
from rest_framework.response import Response
from myapp.models import Course, Flow, User, CCScore
import jwt

from myapp.serializers import CourseSer, ScoreSer
from myapp.edu_user import get_tree, dictfetchall

# 导入原生sql模块
from django.db import connection


# 添加课程
class AddCourse(APIView):

	def post(self,request):

		course_name = request.POST.get('course_name',None)
		price = request.POST.get('price',None)
		user_id = request.POST.get('uid',None)
		pid = request.POST.get('cate_id',None)
		video = request.POST.get('video',None)
		token = request.POST.get('token',None)


		decode_str = jwt.decode(token,'SECRET_KEY',algorithm=['HS256'])
		data = decode_str.get('data',0)
		uid = data.get('uid',0)

		print(user_id)
		print(uid)

		if int(uid) == int(user_id):
	        # 入库操作
			course = Course(course_name=course_name,price=price,user_id=user_id,pid=pid,video=video)

			# 保存
			course.save()

			return Response({'code':200,'message':'ok'})
		else:
			return Response({'code':400,'message':'no'})


# 课程列表
class CourseList(APIView):

	def get(self,request):

		# 当前页
		page = request.GET.get('page',1)

		# 每页展示条数
		size = request.GET.get('size',1)

		# 开始位置
		data_start = (int(page)-1) * int(size)

		# 结束位置
		data_end = int(page) * int(size)

		# 查询
		courselist = Course.objects.all()[data_start:data_end]

		# 总条数
		count = Course.objects.count()

		# 序列化
		courselist_ser = CourseSer(courselist,many=True)

		return Response({'total':count,'data':courselist_ser.data})



# 课程详情页1
class ShowCourse(APIView):

	def get(self, request):

		# 连接redis

		r = redis.Redis(host="192.168.99.102",port=6380)


		# 获取课程id
		cid = request.GET.get('cid')

		course = Course.objects.filter(id=cid).first()

		course_ser = CourseSer(course)

		return Response(course_ser.data)


# 课程详情页2
class CourseDetail(APIView):

	def get(self, request):

		# 获取课程id
		id = request.GET.get('id',None)

		course = Course.objects.get(pk=id)

		course_ser = CourseSer(course)

		return Response(course_ser.data)



# 展示课程分类
class CourseCate(APIView):

	def get(self, request):

		# 建立查询游标
	    cursor = connection.cursor()
	    # 指行sql语句
	    cursor.execute('SELECT * from cate')
	    # 获取结果集
	    res = dictfetchall(cursor)
	    # 强转
	    res=get_tree(res)
	    return HttpResponse(json.dumps(res, indent=4, ensure_ascii=False), content_type='application/json')


# 获取关注状态
class GetFlow(APIView):

	def get(self, request):

		#获取课程id
		id = request.GET.get('id',None)
		uid = request.GET.get('uid',None)

		flow = Flow.objects.filter(uid=uid,course_id=id).first()

		if flow:
			return Response({'state':'true'})

		else:
			return Response({'state':'flase'})

	def post(self,request):

		# 获取数据
		checked = request.POST.get('checked',None)
		id = request.POST.get('id',None)
		uid = request.POST.get('uid',None)

		if checked == 'true':

			user_obj = User.objects.get(id=uid)
			course_obj = Course.objects.get(id=id)

			flow = Flow.objects.filter(uid=uid,course_id=id).first()
			flow.delete()

			return Response({'code':201,'message':'已取消关注'})

		else:
			
			flow = Flow(uid=uid,course_id=id)
			flow.save()
			return Response({'code': 200,'message':'关注成功'})


# 展示用户关注的课程
class UserCourse(APIView):

	def get(self, request):

		# 获取数据
		uid = request.GET.get('uid')

		# 建立查询游标
		cursor = connection.cursor()

		sql = 'SELECT c.course_name from course c left join flow f on c.id = f.course_id left join user u on u.id = f.uid where u.id = %s;' % (uid)

		print(sql)
		# 指行sql语句
		cursor.execute(sql)

		# 获取结果集
		res = dictfetchall(cursor)
		
		return Response(res)



# 打分接口
class Score(APIView):

	def post(self, request):

		# 获取数据
		value = request.POST.get('value')
		uid = request.POST.get('uid')
		cid = request.POST.get('cid')

		score = CCScore.objects.filter(uid=uid,cid=cid).first()
		if score:
			score.score = value
			score.save()

			return Response({'code':200,'message':'打分成功'})
		else:
			score_obj = CCScore(uid=uid,cid=cid,score=value)
			score_obj.save()

			return Response({'code':200,'message':'打分成功'})

	def get(self, request):

		uid = request.GET.get('uid')
		cid = request.GET.get('cid')

		score = CCScore.objects.filter(uid=uid,cid=cid).first()
		if score:
			score_ser = ScoreSer(score)
			return Response(score_ser.data)
		else:
			return Response({'code':405})


# 课程平均分
class ScoreAvg(APIView):

	def get(self, request):

		cid = request.GET.get('cid')

		# 创建查询游标
		cursor = connection.cursor()

		sql = 'select avg(score) from score s where cid=%s' % (cid)
		print(sql)

		# 执行sql
		cursor.execute(sql)

		# 获取结果集
		res = dictfetchall(cursor)

		return Response(res)

